﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    public partial class CommunityDetailPage : PhoneApplicationPage
    {
        private int comicId = 0, discussId = 0, comicUserId = 0, replyUserId = 0;
        private int pageIndex = 1;//默认从1开始
        private JsonComicCommunityDetailReplayInfo currentSelectedItem = null;
        private bool IsLastPage = false;
        // 数据加载的标识
        public bool IsLoading = false;
        // 线程锁的对象
        private object o = new object();
        private bool IsNeedReloaded = false;

        public CommunityDetailPage()
        {
            InitializeComponent();
            this.IsNeedReloaded = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.IsNeedReloaded = false;
            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string value;
            base.NavigationContext.QueryString.TryGetValue("comicId", out value);
            int.TryParse(value, out comicId);

            //
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            //GetIMEI();
            if (this.IsNeedReloaded)
                LoadDiscussData(comicId);
        }

        void LoadDiscussData(int comicId)
        {
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);

            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/getdiscussinfo?id=", comicId, "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            //
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityDetail>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null))
                {
                    MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        this.gridDiscuss.DataContext = rootCharacterString.Info;
                        this.discussId = rootCharacterString.Info.Id;
                        this.replyUserId = rootCharacterString.Info.Userid;
                        this.LoadReplayData(discussId);
                    });
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityDetail>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                this.gridDiscuss.DataContext = rootCharacterString.Info;
                                this.discussId = rootCharacterString.Info.Id;
                                this.replyUserId = rootCharacterString.Info.Userid;
                                this.LoadReplayData(discussId);
                            });
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void LoadReplayData(int discussId, int pageIndex = 1)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST,
                string.Format("/comic/getreplylist?discussid={0}&pageno={1}&pagesize={2}&e={3}", discussId, pageIndex, KEYS.PAGE_SIZE, DateTime.Now.Ticks),
                "&", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(string.Concat("pageIndex=", pageIndex, "\t", requestUrl), this.GetType(), MethodBase.GetCurrentMethod());

            //string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            //LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            //cacheHelper.GetDataFromLocalCache(cacheDataKey);
            //if (!cacheHelper.IsReload)
            //{
            //    var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityDetailReplay>(cacheHelper.LocalCacheData);
            //    if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
            //    {
            //        MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
            //    }
            //    else
            //    {
            //        var items = rootCharacterString.Info;
            //        if (items != null && items.Count > 0)
            //        {
            //            BindReplayData(items);
            //        }
            //    }
            //    this.psbStatus.CloseStatusBar();
            //    return;
            //}


            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            IsLastPage = true;
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunityDetailReplay>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var items = rootCharacterString.Info;
                            if (items != null && items.Count > 0)
                            {
                                //cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                BindReplayData(items);
                            }
                        }

                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        void BindReplayData(ObservableCollection<JsonComicCommunityDetailReplayInfo> items)
        {
            if (!(items != null && items.Count > 0))
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if (pageIndex > 1)
                {
                    if (this.lls.ItemsSource != null && this.lls.ItemsSource.Count > 0)
                    {
                        foreach (var item in items)
                        {
                            this.lls.ItemsSource.Add(item);
                        }
                    }
                    else
                    {
                        this.lls.ItemsSource = items;
                    }
                }
                else
                {
                    this.lls.ItemsSource = items;
                }
            });
        }

        private void lls_ItemRealized(object sender, ItemRealizationEventArgs e)
        {
            lock (o)
            {
                if (IsLoading)
                    return;
                if (e.ItemKind != LongListSelectorItemKind.Item)
                    return;
                currentSelectedItem = e.Container.Content as JsonComicCommunityDetailReplayInfo;
                int selectedIndex = this.lls.ItemsSource.IndexOf(currentSelectedItem);
                int total = this.lls.ItemsSource.Count;
                if (total - selectedIndex <= 2)
                {
                    // 设置IsLoading为true，在加载数据的过程中，禁止多次进入
                    IsLoading = true;
                    if (IsLastPage)
                    {
                        if (total > KEYS.PAGE_SIZE)
                        {
                            //超过一页时才提示
                            MessageToastManager.Show(AppResources.DataNoMore);
                        }
                        // 修改加载的状态
                        IsLoading = false;

                    }
                    else
                    {
                        this.pageIndex += 1;
                        this.LoadReplayData(this.discussId, pageIndex);
                        // 修改加载的状态
                        IsLoading = false;
                    }
                }
            }
        }

        private CustomMessageBox messageBox = null;
        private string msgReplayContent = string.Empty;
        private void appBarWrite_Click(object sender, EventArgs e)
        {
            ThirdUserLogin();
            if (this.comicUserId <= 0)
                return;

            TextBox txtInfo = new TextBox()
            {
                MinHeight = 120,
                MaxHeight = 120,
                TextWrapping = TextWrapping.Wrap,
                VerticalScrollBarVisibility = ScrollBarVisibility.Visible,
                AcceptsReturn = true
            };
            if (string.IsNullOrWhiteSpace(msgReplayContent))
                txtInfo.Text = AppResources.CommunityReplayInputContent;
            else
                txtInfo.Text = msgReplayContent;
            txtInfo.Style = Application.Current.Resources["TextBoxStyleComic"] as Style;//支持内容滚动
            txtInfo.GotFocus += txtInfo_GotFocus;
            txtInfo.LostFocus += txtInfo_LostFocus;
            TiltEffect.SetIsTiltEnabled(txtInfo, true);
            messageBox = new CustomMessageBox()
            {
                VerticalAlignment = System.Windows.VerticalAlignment.Bottom,
                Caption = "撰写评论",
                Content = txtInfo,
                LeftButtonContent = "发表",
                RightButtonContent = "取消"
            };
            messageBox.Style = Application.Current.Resources["CustomMessageBoxStyleComic"] as Style;
            messageBox.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        if (string.IsNullOrWhiteSpace(txtInfo.Text.Trim()) || AppResources.CommunityReplayInputContent.Equals(txtInfo.Text.Trim()))
                        {
                            MessageToastManager.Show("不能为空！");
                            return;
                        }
                        msgReplayContent = txtInfo.Text.Trim();
                        this.AddReply(msgReplayContent);
                        break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                    default:
                        break;
                }
            };

            messageBox.Show();
        }

        void ThirdUserLogin()
        {
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.KEY_UserThirdLoginInfo))
            {
                ConfirmThirdUserLogin();
                return;

            }

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.KEY_UserThirdLoginInfo);
            if (string.IsNullOrWhiteSpace(localCacheData))
            {
                ConfirmThirdUserLogin();
                return;
            }
            var userInfo = JSONHelper.Deserialize<UserThirdLoginInfo>(localCacheData);
            if (userInfo == null)
            {
                ConfirmThirdUserLogin();
                return;
            }
            if (userInfo.ComicUserId <= 0)
            {
                ConfirmThirdUserLogin();
                return;
            }

            this.comicUserId = userInfo.ComicUserId;
        }

        void ConfirmThirdUserLogin()
        {
            this.oauthControl.OnClose += delegate(object sender, EventArgs e)
            {
                this.popupLogin.IsOpen = false;
            };
            this.popupLogin.IsOpen = true;
        }

        void AddReply(string content)
        {
            if (!(this.comicUserId > 0 && !string.IsNullOrWhiteSpace(content) && this.discussId > 0 && this.replyUserId > 0))
            {
                MessageToastManager.Show("回复数据有误，请重试！");
                return;
            }

            //{"content":"最近都没有","userid":"247460","replyuserid":"181816","discussid":"145751"}
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/addreply", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("content", content);
            parameters.Add("userid", this.comicUserId);
            parameters.Add("replyuserid", this.replyUserId);
            parameters.Add("discussid", this.discussId);

            PostClientHelper proxy = new PostClientHelper(parameters);
            proxy.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    return;
                }

                #region 获取结果处理
                string result = e.Result;

                if (string.IsNullOrWhiteSpace(result))
                {
                    LogHelper.LogError("Result is empty.");
                    //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                    return;
                }
                //
                if (result.StartsWith("exception:"))
                {
                    LogHelper.LogError(result);
                    //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                    return;
                }

                LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                //
                var rootCharacterString = JSONHelper.Deserialize<JsonAddFeedBack>(result);
                if (KEYS.JSON_SUCCESS == rootCharacterString.Code)
                {
                    MessageToastManager.Show("操作成功！");
                    this.msgReplayContent = string.Empty;
                    this.lls.ItemsSource = null;
                    this.pageIndex = 1;
                    this.LoadReplayData(this.discussId);//强制刷新本地缓存
                }
                else
                {
                    MessageToastManager.Show("操作失败！");
                    LogHelper.LogError("操作失败:\t" + rootCharacterString.CodeMsg);
                }

                #endregion 获取结果处理
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }

        void txtInfo_LostFocus(object sender, RoutedEventArgs e)
        {
            if (messageBox != null)
            {
                messageBox.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (string.IsNullOrWhiteSpace(txtControl.Text.Trim()))
                {
                    txtControl.Text = AppResources.CommunityReplayInputContent;
                }
            }
        }

        void txtInfo_GotFocus(object sender, RoutedEventArgs e)
        {
            if (messageBox != null)
            {
                messageBox.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                var txtControl = sender as TextBox;
                if (txtControl == null)
                    return;
                if (AppResources.CommunityReplayInputContent.Equals((sender as TextBox).Text))
                {
                    txtControl.Text = string.Empty;
                }
            }
        }

        private void Grid_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Complete();
            if (e.CumulativeManipulation.Translation.Y > 0)
            {
                //从下往上拉时不处理
                return;
            }

            if (IsLastPage)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    Helper.PageShowDataNoMore<JsonComicCommunityDetailReplayInfo>(sender, this.lls);
                });
            }
        }




    }
}